﻿using System;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WeBlog.Models;

namespace WeBlog.Controllers
{
    public class BlogPostController : Controller
    {

        public ActionResult Details(int blogPostId)
        {
            var blogPost = BlogRepository.Instance.GetBlogPostById(blogPostId);
            var comments = BlogRepository.Instance.GetBlogPostComments(blogPostId);

            var model = new BlogPostModel(blogPost,comments);

            return View(model);
        }

        [HttpPost]
        public ActionResult Details(BlogPostModel model)
        {
            if (ModelState.IsValid)
            {
                model.NewComment.BlogPostId = Convert.ToInt32(Request["blogPostId"]);
                model.NewComment.BlogDateTime = DateTime.Now;
                BlogRepository.Instance.CreateBlogPostComment(model.NewComment);
            }
            return RedirectToAction("Details", "BlogPost", new { blogPostId = model.NewComment.BlogPostId });
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(BlogPost blogPost)
        {
            if (Request.Files != null)
            {
                HttpPostedFileBase file = Request.Files[0];
                if (file.ContentLength > 0)
                {
                    string filename = Path.GetFileName(file.FileName);
                    string directory = Server.MapPath("~/Upload/Images");
                    if (filename != null) 
                        file.SaveAs(Path.Combine(directory,filename));
                }
            }
                BlogRepository.Instance.CreateBlogPost(blogPost);
                return RedirectToAction("Index", "Home");
    
        }

    }
}